import { PlusOutlined } from '@ant-design/icons';
import { Button, message, TreeSelect, Divider, Popconfirm } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import Bmap from '@/components/Bmap/index.jsx';
import { transTitle } from '@/utils/utils';
import FormItem from 'antd/lib/form/FormItem';
import styles from '../../global.less';
import {
  queryRule,
  updateRule,
  addRule,
  removeRule,
  queryCommunityRule,
  queryStreetRule,
} from './service';
import Access from '@/components/Access/Access';
/**
 * 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 * @param payload
 */

const handleUpdate = async (payload) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule(payload);
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */

const handleRemove = async (selectedRows, actionRef) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;

  try {
    await removeRule(selectedRows.id);
    hide();
    message.success('删除成功，即将刷新');
    actionRef.current.reload();

    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [createEditModalVisible, handleEditModalVisible] = useState(false);
  const [createMapModalVisible, handleMapModalVisible] = useState(false);
  const [createCommunityModalVisible, handleCommunityModalVisible] = useState(false);
  const [formValue, setFormValue] = useState(null);
  const [pointData, setPointData] = useState({});
  const [count, setCount] = useState({});
  const [treeValue, setTreeValues] = useState([]);
  const [menuValues, setMenuValues] = useState([]);
  const [communityCount, setCommunityCount] = useState({});
  const [mapValue, setMapValue] = useState({});
  const [policeValues, setPoliceValues] = useState([]);
  const [streetValues, setStreetValues] = useState([]);
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const handleChoicePlace = (e) => {
    if (e.hasOwnProperty('point')) {
      setPointData(e);
    }
  };

  const handleQueryStreet = async () => {
    try {
      const response = await queryStreetRule({ type: 5 });
      const { data } = response;
      setStreetValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const handleQueryArea = async () => {
    try {
      const response = await queryRule({ type: 1 });
      const { data } = response;
      transTitle(data);
      setMenuValues(data);
      return true;
    } catch (error) {
      return false;
    }
  };
  const TreeOnChange = (value) => {
    setTreeValues(value);
  };
  // useEffect(() => {
  //   // handleQueryStreet();
  //   // handleQueryPolice();
  //   // handleQueryArea();
  // }, []);
  const columns = [
    {
      title: '部门名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '所属公司',
      dataIndex: 'companyName',
      valueType: 'text',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '负责人企微',
      dataIndex: 'leader',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '助理',
      dataIndex: 'helperName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '助理企微',
      dataIndex: 'helper',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '分管会计',
      dataIndex: 'accounterName',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '分管会计企微',
      dataIndex: 'accounter',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '父级',
      dataIndex: 'parentId',
      valueType: 'text',
      hideInSearch: true,
      hideInTable: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return (
          <FormItem label={false}>
            <TreeSelect
              showSearch
              // style={{ width: '400px' }}
              value={treeValue}
              dropdownStyle={{ maxHeight: 800, overflow: 'auto' }}
              placeholder="请选择职位"
              allowClear
              treeDataSimpleMode
              treeData={menuValues}
              treeNodeFilterProp="title"
              treeNodeLabelProp="title"
              onChange={TreeOnChange}
            />
          </FormItem>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 140,
      render: (_, record) => (
        <>
          <Access accessKey={"@updateDept"}>
            <a
              onClick={() => {
                handleEditModalVisible(true);
                setPointData({
                  address: record.address,
                  point: {
                    lat: record.lat,
                    lng: record.lng,
                  },
                });
                setFormValue(record);
              }}
            >
              修改
            </a>
            <Divider type="vertical" />
          </Access>
          <Access accessKey={"@deleteDept"}>
            <Popconfirm
              title="确定删除机构吗?"
              onConfirm={() => {
                handleRemove(record, actionRef);
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>
          </Access>

        </>
      ),
    },
  ];
  const communityColumns = [
    // {
    //   title: '序号',
    //   dataIndex: 'id',
    //   valueType: 'text',
    //   hideInForm: true,
    // },
    {
      title: '部门名称',
      dataIndex: 'name',
      valueType: 'text',
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'text',
      hideInSearch: true,
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="部门列表"
        actionRef={actionRef}
        rowKey="id"
        bordered
        toolBarRender={() => [
          <Access accessKey={"@newDept"}>
            <Button
              type="primary"
              onClick={() => {
                handleQueryArea();
                return handleModalVisible(true);
              }}
            >
              <PlusOutlined /> 新增
            </Button>
          </Access>
          ,
        ]}
        search={{
          labelWidth: 120,
        }}
        request={(params, sorter, filter) => {
          return queryRule({ ...params, sorter, filter });
        }}
        beforeSearchSubmit={(payload) => {
          if (payload.address) {
            payload.parentId = payload.address.value;
          }
          delete payload.address;
          return payload;
        }}
        postData={(params) => {
          setCount(params.length);
          return params||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
        rowSelection={false}
        // options={false}
      />
      <CreateForm
        title="新增机构"
        onCancel={() => handleModalVisible(false)}
        modalVisible={createModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          form={{
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        title="修改部门信息"
        onCancel={() => handleEditModalVisible(false)}
        modalVisible={createEditModalVisible}
        width={800}
      >
        <ProTable
          className={styles.formModal}
          onSubmit={async (value) => {
            value.id = formValue.id;
            const success = await handleUpdate(value);

            if (success) {
              handleEditModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          rowKey="id"
          bordered
          type="form"
          columns={columns}
          form={{
            initialValues: formValue,
            layout: 'horizontal ',
            labelAlign: 'rihgt',
            labelCol: { span: 8 },
            wrapperCol: { span: 24 },
          }}
        />
      </CreateForm>
      <CreateForm
        onCancel={() => handleMapModalVisible(false)}
        modalVisible={createMapModalVisible}
        title="机构位置"
      >
        <Bmap size={{ width: 400, height: 350, marginLeft: '8%' }} value={mapValue} />
      </CreateForm>
      <CreateForm
        title="关联关系"
        onCancel={() => handleCommunityModalVisible(false)}
        modalVisible={createCommunityModalVisible}
        width={1200}
      >
        <ProTable
          headerTitle="硬件列表"
          // actionRef={actionRef}
          bordered
          rowKey="id"
          search={{
            labelWidth: 80,
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              onClick={() => {
                // handleModalVisible(true);
                const payload = { version: row.version + 1, id: row.id };
                const details = [];
                selectedRowsState.map((item) => {
                  details.push({ id: item.id });
                });
                payload.details = details;
                handleUpdate(payload);
                handleCommunityModalVisible(false);
              }}
            >
              <PlusOutlined /> 确定
            </Button>,
          ]}
          options={false}
          request={(params, sorter, filter) => {
            params.type = 6;
            return queryCommunityRule({ ...params, sorter, filter });
          }}
          pagination={{
            defaultPageSize: 30,
            showSizeChanger: false,
            showTitle: false,
            total: communityCount,
            showTotal: (total) => `共${total}条`,
          }}
          postData={(params) => {
            const { list, total } = params;
            setCommunityCount(total);
            return list||[];
          }}
          columns={communityColumns}
          rowSelection={{
            onChange: (_, selectedRows) => setSelectedRows(selectedRows),
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
